package captcha_logic

import (
	"fmt"
	"strconv"
	"strings"

	"gitee.com/Luna-CY/Golang-Project-Template/internal/context"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/errors"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/logger"
	"github.com/wenlng/go-captcha/v2/click"
)

func (cls *Captcha) CheckClickCaptcha(ctx context.Context, key string, dots string, destory bool) errors.Error {
	var data map[int]*click.Dot
	if err := cls.cache.Get(ctx, fmt.Sprintf("captcha:%s", key), &data); nil != err {
		if err.IsType(errors.ErrorTypeRecordNotFound) {
			return err.Relation(errors.New(errors.ErrorTypeInvalidRequest, "IGLCL_IC.C_HA.CCC_HA.160612", "验证码错误，验证码不存在"))
		}

		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("IGLCL_IC.C_HA.CCC_HA.150444 获取验证码缓存数据失败: %v", err)

		return err.Relation(errors.ErrorServerInternalError("IGLCL_IC.C_HA.CCC_HA.170504", "验证码数据获取失败"))
	}

	var dotsData = strings.Split(dots, ",")
	if len(data)*2 != len(dotsData) {
		return errors.New(errors.ErrorTypeInvalidRequest, "IGLCL_IC.C_HA.CCC_HA.270714", "验证码错误，格式无效")
	}

	// 验证点位坐标
	for i, dot := range data {
		x, err := strconv.ParseInt(dotsData[i*2], 10, 64)
		if nil != err {
			return errors.New(errors.ErrorTypeInvalidRequest, "IGLCL_IC.C_HA.CCC_HA.340910", "验证码错误，格式无效")
		}

		y, err := strconv.ParseInt(dotsData[i*2+1], 10, 64)
		if nil != err {
			return errors.New(errors.ErrorTypeInvalidRequest, "IGLCL_IC.C_HA.CCC_HA.390926", "验证码错误，格式无效")
		}

		if !click.CheckPoint(x, y, int64(dot.X), int64(dot.Y), int64(dot.Width), int64(dot.Height), 0) {
			return errors.New(errors.ErrorTypeInvalidRequest, "IGLCL_IC.C_HA.CCC_HA.431111", "验证码错误")
		}
	}

	if destory {
		// 销毁验证码
		if err := cls.cache.Delete(ctx, fmt.Sprintf("captcha:%s", key)); nil != err {
			logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("IGLCL_IC.C_HA.CCC_HA.511240 销毁验证码缓存数据失败: %v", err)
		}
	}

	return nil
}
